package com.gxa.community.customer.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.community.core.common.CommonVar;
import com.gxa.community.core.exception.BusinessException;
import com.gxa.community.core.exception.ExceptionCode;
import com.gxa.community.core.pojo.dto.login.UserInfo;
import com.gxa.community.customer.config.RedisUtils;
import com.gxa.community.customer.thread.UserLocalThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    RedisUtils redisUtils;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
           throw new BusinessException(ExceptionCode.EMPTY_TOKEN);
        }else{
            RestTemplate template = new RestTemplate();
            MultiValueMap<String,String> map = new LinkedMultiValueMap<>();
            map.add("token",token);
            HttpHeaders http = new HttpHeaders();
            http.add("Content-Type","application/x-www-form-urlencoded");
            HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<>(map,http);
            Map map1 = template.postForObject("http://localhost:8090/user/token", httpEntity, Map.class);
            System.out.println(map1);
            if (!map1.get("code").equals("200")){
                throw new BusinessException(ExceptionCode.SERVER_FAILED);
            }
            //对后端进行拦截
            UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(CommonVar.AGENT_LOGIN_AXLAB_TOKEN + token);
            //设置全局id
            request.setAttribute("userId", userInfo.getUserId());

            Object msg = map.get("msg");
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(msg);
            new UserLocalThread().set(jsonString);

            return true;
        }
    }
}
